package com.taotao.portal.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.utils.JsonUtils;
import com.taotao.pojo.TbItemDesc;
import com.taotao.pojo.TbItemParamItem;
import com.taotao.portal.pojo.ItemInfo;
import com.taotao.portal.service.ItemService;

@Controller
@RequestMapping("/item")
public class ItemController {
	
	@Autowired
	private ItemService itemService;
	
	@RequestMapping("/{id}")
	public String itemInfo(@PathVariable Long id,Model model) throws Exception {
		
		ItemInfo itemInfo = itemService.getItemInfoById(id);
		model.addAttribute("item",itemInfo);
		return "item";
	}
	
	@RequestMapping(value = "/desc/{id}" ,produces=MediaType.TEXT_HTML_VALUE+";charset=utf-8")
	@ResponseBody
	public String itemDesc(@PathVariable Long id) throws Exception {
		
		TbItemDesc itemDesc = itemService.getItemDescById(id);
		return itemDesc.getItemDesc();
	}
	
	@RequestMapping(value = "/param/{id}",produces=MediaType.TEXT_HTML_VALUE+";charset=utf-8")
	@ResponseBody
	public String itemParam(@PathVariable Long id) throws Exception {
		
		TbItemParamItem itemParam = itemService.getItemParamById(id);
		String paramData = itemParam.getParamData();
		//生成html
		// 把规格参数json数据转换成java对象
		List<Map> jsonList = JsonUtils.jsonToList(paramData, Map.class);
		StringBuffer sb = new StringBuffer();
		sb.append("<table cellpadding=\"0\" cellspacing=\"1\" width=\"100%\" border=\"0\" class=\"Ptable\">\n");
		sb.append("    <tbody>\n");
		for(Map m1:jsonList) {
			sb.append("        <tr>\n");
			sb.append("            <th class=\"tdTitle\" colspan=\"2\">"+m1.get("group")+"</th>\n");
			sb.append("        </tr>\n");
			List<Map> list2 = (List<Map>) m1.get("params");
			for(Map m2:list2) {
				sb.append("        <tr>\n");
				sb.append("            <td class=\"tdTitle\">"+m2.get("k")+"</td>\n");
				sb.append("            <td>"+m2.get("v")+"</td>\n");
				sb.append("        </tr>\n");
			}
		}
		sb.append("    </tbody>\n");
		sb.append("</table>");
		//返回html片段
		return sb.toString();
	}
		
	
}
